from django.template.loader import render_to_string
from django.template import RequestContext
from django import template
from garetjax.menu.models import Menu

register = template.Library()

def render_menu(parser, token):
    try:
        tag_name, menu, template_name = token.split_contents()
    except ValueError:
        try:
            tag_name, menu = token.split_contents()
            template_name = '"menu/menu.html"'
        except ValueError:
            raise template.TemplateSyntaxError, "%r tag requires one ore two arguments" % token.contents.split()[0]
    
    return MenuRenderer(menu, template_name)

class MenuRenderer(template.Node):
    def __init__(self, menu, template_name):
        self.menu = template.Variable(menu)
        self.template_name = template.Variable(template_name)
        
    def render(self, context):
        request = template.Variable('request').resolve(context)
        
        try:
            menu_name = self.menu.resolve(context)
            menu = Menu.objects.get(name=menu_name)
        except (template.VariableDoesNotExist, Menu.DoesNotExist):
            return ''
            
        c = RequestContext(request, {
            'menu': menu,
        })

        return render_to_string(self.template_name.resolve(context), c)
        
register.tag('menu', render_menu)